package code16_thread;

import java.util.HashMap;

public class Test10 {

	private static int m = 10;
	// 管理线程本地变量
	//static HashMap<Thread, String> threadLocal = new HashMap<Thread, String>();
	
	// jdk 提供的 线程本地工具类
	static ThreadLocal<String> threadLocal = new ThreadLocal<String>();
	
	public static void main(String[] args) {
//		m = 100;
//		System.out.println("main:"+m);
		
//		f1();
		
		
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				Thread thread = Thread.currentThread();
				String val = Math.random()+"";
				System.out.println(thread.getName()+" 设置值:" + val);
				//threadLocal.put(thread, val);
				threadLocal.set(val);// 设置当前线程的对应变量值
				
				f3();// 执行某个方法
				
				//System.out.println(thread.getName()+" 取值(run):"+threadLocal.get(thread));
				// 获取当前线程对应的变量值
				System.out.println(thread.getName()+" 取值(run):"+threadLocal.get());
			}
		}, "t1");
		
		t1.start();
		
		Thread thread = Thread.currentThread();
		String val = Math.random()+"";
		System.out.println(thread.getName()+" 设置值:" + val);
		//threadLocal.put(thread, val);
		threadLocal.set(val);
		
		f3();// 执行某个方法
		
	}
	
	public static void f3() {
		Thread thread = Thread.currentThread();
		//System.out.println(thread.getName()+" 取值(f3):"+threadLocal.get(thread));
		System.out.println(thread.getName()+" 取值(f3):"+threadLocal.get());
		
		// 删除当前线程对应的变量
		threadLocal.remove();
	}
	
//	public static void f1() {
//		System.out.println("f1:"+m);
//	}
	
}

class Test111 {
	public static void f2() {
		
	}
}